//
//  LoginViewController.m
//  QRMaster
//
//  Created by myApple on 15/3/20.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "StartPageController.h"
#import "StartPageView.h"
#import "ForgetPWDViewController.h"
#import "QRTabbarController.h"
#import "MyRsa.h"
#import "RequestNetWork.h"
#import "userInfoModel.h"
#import "RegistLastViewController.h"
#import "RegistFirstStepViewController.h"
#import "Reachability.h"
#import "PromptInfoView.h"
#import "OpertionPlist.h"
#import "OperationDataBaseModel.h"
#import "OpertionPlist.h"
#import "GesturePasswordController.h"
#import "checkPower.h"
#import "MJExtension.h"
#import "CommunityListInfo.h"
#import "QRSingleton.h"
#import "faveriterCard.h"
#import "localizControllerViewController.h"
#import "AreaChooseController.h"
#import "RemembeAccountLoginView.h"
#import "MobileRegistFirstStepController.h"
#import "EmailLoginController.h"
#import "validateInputValue.h"
#import "QRSingleton.h"

@interface StartPageController ()<StartPageViewDelegate,RemembeAccountLoginViewDelegate>
{
    NSMutableDictionary * dict;//存储个人信息的
    UIImageView * logoActivityView;
    NSMutableArray * CommunityArray;
    NSUserDefaults * userInfo;
    QRSingleton * singleton;
    StartPageView * StartView;
    RemembeAccountLoginView * remembeView;
    BOOL _isTrail;//是否试用
    BOOL _isChangeLanguag;//是否是从切换语言那里切换过来的
}

@end

@implementation StartPageController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dict = [[NSMutableDictionary alloc]init];
        CommunityArray = [[NSMutableArray alloc]init];
        singleton = [QRSingleton sharedQRSingleton];
        _isTrail = NO;
        _isChangeLanguag = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self prepareTitleView];
    [self prepareView];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationController.navigationBarHidden = YES;
    userInfo = [NSUserDefaults standardUserDefaults];
    [userInfo setValue:nil forKey:@"token"];
    [userInfo setValue:nil forKey:@"login"];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    [data setValue:nil forKey:HOUSEINFO];
    [data setValue:nil forKey:STAFFINFO];
    [data setValue:nil forKey:COMMUNITYINFOFORKEY];
    [OpertionPlist writeDataToPlist:data];
    GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
    [gpc clear];
    [userInfo setValue:@"0" forKey:@"gesture"];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"])
    {
        self.navigationController.navigationBarHidden = NO;
        [self.navigationItem setHidesBackButton:NO];
        self.title = NSLocalizedString(@"mobileLogin", @"手机登录");
    }
    else
    {
        [self.navigationItem setHidesBackButton:YES];
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationController.navigationBarHidden = YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    }
    if (_isChangeLanguag ||[QRSingleton sharedQRSingleton].loginViewShow) {
        //根据本地是否存过ID号来确定显示那个登录页面,以及是否注册成功或者忘记密码成功
        if (([[NSUserDefaults standardUserDefaults] objectForKey:@"userMobile"] && ![UID isEqualToString:@"4"])) {
            remembeView.hidden = NO;
            [remembeView showUserInfo];
            StartView.hidden = YES;
             [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];//注册成功也不需要启动介绍页面
        }
        else
        {
            remembeView.hidden = YES;
            StartView.hidden = NO;
        }
    }
    [QRSingleton sharedQRSingleton].loginViewShow = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
}

-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"])
    {
        height = ScreenHeight - 64;
    }
    else
    {
        y = 64;
        height = ScreenHeight - 64;
    }
    
    StartView = [[StartPageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    StartView.delegate = self;
    [self.view addSubview:StartView];
    
    
    remembeView = [[RemembeAccountLoginView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    remembeView.delegate = self;
    [self.view addSubview:remembeView];
}

-(void)getLoginData:(NSString *)account PassWord:(NSString *)password areaCode:(NSString *)code
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSString * urlString = nil;
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    if (!_isTrail) {
        [postDict setValue:account forKey:@"account"];
        [postDict setValue:[self getPassword:password] forKey:@"passwd"];
        urlString = POST(LOGIN);
        
    }
    else
    {
         urlString = POST(TRAIL);
        _isTrail = NO;
    }
    if ([validateInputValue isPureNumandCharacters:account])
    {
        [postDict setValue:code forKey:@"areaCode"];
    }

    [rnk initWithPath:urlString params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            userInfoModel * model = [userInfoModel mj_objectWithKeyValues:[downLoadData objectForKey:@"data"]];
            model.uid = [[downLoadData objectForKey:@"data"] objectForKey:@"id"];
            if (![model.uid isEqualToString:[userInfo objectForKey:@"uid"]]) {
                //不是同一个人登录就去掉本地相关数据
                NSMutableDictionary * fileData = [OpertionPlist readDataFromPlist];
                [fileData setValue:nil forKey:FAVERITCARD];
                [OpertionPlist writeDataToPlist:downLoadData];
                //清除表信息
                OperationDataBaseModel * opData = [[OperationDataBaseModel alloc]init];
                [opData truncateTable];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"communityId"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                singleton.communityName = @"";
            }
            [userInfo setObject:model.uid forKey:@"uid"];
            [userInfo setObject:model.token forKey:@"token"];
            [userInfo setValue:code forKey:@"areaCode"];
            [userInfo setObject:@"logined" forKey:@"login"];//是否登录过来判断手势密码的显示问题
            [userInfo setValue:@"1" forKey:@"guestureCount"];//解决手势密码黑屏问题
            if ([validateInputValue isPureNumandCharacters:account]){
                 [userInfo setObject:model.mobile forKey:@"userMobile"];//记住登录号码
            }
            else
            {
                 [userInfo setObject:model.email forKey:@"userMobile"];//记住登录邮箱
            }
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];//不要启动介绍页面
            [userInfo synchronize];
            [self getCommunityData];
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    }];
    
}

-(NSString *)getPassword:(NSString *)password
{
    MyRsa * rsa = [[MyRsa alloc]init];
    if (rsa != nil) {
        NSString * encryptPWD = [rsa RSAEncrypotoTheData:[NSString stringWithFormat:@"12345678%@",password] key:publicKeyString];
        encryptPWD = [encryptPWD stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return encryptPWD;
    }
    else
        return nil;
    
}


#pragma mark -- 获取集群信息
-(void)getCommunityData
{
    if ([self IsHaveNetwork]) {
        return;
    }
//    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
//        [self stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            CommunityListInfo * listInfo = [[CommunityListInfo alloc]init];
           NSDictionary * communityData = [data objectForKey:@"data"];
            CommunityArray = [communityData objectForKey:@"communities"];
            if (CommunityArray.count > 0) {
                for (int i=0; i<CommunityArray.count; i++) {
                    [listInfo deleteCommunityListInfo:[[CommunityArray objectAtIndex:i] objectForKey:@"communityid"]];
                     [listInfo insertCommunityListInfo:[[CommunityArray objectAtIndex:i] objectForKey:@"communityid"] withCommunityName:[[CommunityArray objectAtIndex:i] objectForKey:@"communityname"] withCommunityAreaCode:[[CommunityArray objectAtIndex:i] objectForKey:@"areaCode"]];
        
                }
                if([[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"] == nil )
                {
                    singleton.communityId = [CommunityArray[0]objectForKey:@"communityid"];
                    singleton.communityName = [CommunityArray[0] objectForKey:@"communityname"];
                    singleton.currentAreaCodeString = [CommunityArray[0]objectForKey:@"areaCode"];
                    singleton.roleIndex = [[CommunityArray[0] objectForKey:@"role"]integerValue];
                    [[NSUserDefaults standardUserDefaults]setObject:singleton.communityId forKey:@"communityId"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                else
                {
                    singleton.communityId = [[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"];
                    for (NSDictionary * commDict in CommunityArray) {
                        if ([singleton.communityId isEqualToString:[commDict objectForKey:@"communityid"]]) {
                            singleton.currentAreaCodeString = [commDict objectForKey:@"areaCode"];
                            singleton.roleIndex = [[commDict objectForKey:@"role"]integerValue];
                            singleton.communityName = [commDict objectForKey:@"communityname"];
                        }
                    }
                }
                
//                [self getFaveriterCard];
                QRTabbarController * qrtc = [[QRTabbarController alloc]init];
                [self.navigationController pushViewController:qrtc animated:YES];
                qrtc.navigationController.navigationBarHidden = YES;
            }
        }
        else if (error != nil) {
            
            if ([[error objectForKey:@"status"] integerValue] == 210) {//没有添加任何集群
                QRTabbarController * qrtc = [[QRTabbarController alloc]init];
                [self.navigationController pushViewController:qrtc animated:YES];
                qrtc.navigationController.navigationBarHidden = YES;
                singleton = nil;
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
            
        }
//        [loadImg stop];
    };
    
}

#pragma mark -- 获取网络收藏房卡信息
-(void)getFaveriterCard
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETCOLLECTROOM) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            [faveriterCard writeFaveriterCard:[downLoadData objectForKey:@"data"]];
        }
        QRTabbarController * qrtc = [[QRTabbarController alloc]init];
        [self.navigationController pushViewController:qrtc animated:YES];
        qrtc.navigationController.navigationBarHidden = YES;
    }];
    
}

#pragma mark --- startpageviewdelegate
-(void)Login:(NSString *)uid PassWord:(NSString *)password areaCode:(NSString *)code
{
    [self getLoginData:uid PassWord:password areaCode:code];
}

-(void)Resgsit
{
    MobileRegistFirstStepController * mrfsc = [[MobileRegistFirstStepController alloc]init];
    [self.navigationController pushViewController:mrfsc animated:YES];
    _isChangeLanguag = NO;
}

-(void)loginByEamil
{
    EmailLoginController * elc = [[EmailLoginController alloc]init];
    [self.navigationController pushViewController:elc animated:YES];
    _isChangeLanguag = NO;
}

-(void)trial
{
    _isTrail = YES;
    [self getLoginData:@"" PassWord:@"" areaCode:nil];
}


-(void)ForgetPassWord
{
    ForgetPWDViewController * fvwc = [[ForgetPWDViewController alloc]init];
    [self.navigationController pushViewController:fvwc animated:YES];
    _isChangeLanguag = NO;

}

-(void)choiceArea
{
    AreaChooseController * acc = [[AreaChooseController alloc]init];
    [self.navigationController pushViewController:acc animated:YES];
     _isChangeLanguag = NO;
    acc.areaCode = ^(NSString * areaCodeId,NSString * areaOrCountry)
    {
        [StartView.areaTextBtn setTitle:areaOrCountry forState:0];
        StartView.areaCodeTextField.text = areaCodeId;
    };
}



#pragma mark --------------- RemembeAccountLoginViewDelegate
-(void)changeLanguageRem
{
    localizControllerViewController * lcv = [[localizControllerViewController alloc]init];
    [self.navigationController pushViewController:lcv animated:YES];
}

-(void)remWithLogin:(NSString *)uid PassWord:(NSString *)password
{
    [self getLoginData:uid PassWord:password areaCode:AREACODE];
}

-(void)ForgetPassWordRem
{
    ForgetPWDViewController * fvwc = [[ForgetPWDViewController alloc]init];
    [self.navigationController pushViewController:fvwc animated:YES];
}

-(void)ResgsitRem
{
    MobileRegistFirstStepController * mrfsc = [[MobileRegistFirstStepController alloc]init];
    [self.navigationController pushViewController:mrfsc animated:YES];
}

-(void)changeAccountRem
{
    remembeView.hidden = YES;
    StartView.hidden = NO;
}


-(void)dealloc
{
   [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
